﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using YTSK.Common;

namespace YTSK
{
    public static class DatatableExt
    {
        public static T ToObj<T>(this DataRow dtr)
        {
            var obj = Activator.CreateInstance<T>();
            Type t = obj.GetType();
            PropertyInfo[] ps = t.GetProperties();
            foreach (PropertyInfo p in ps)
            {
                string pname = p.Name;
                if (dtr.Table.Columns.Contains(pname))
                {
                    var val = dtr[pname];
                    if (val != DBNull.Value)
                    {
                        var bset = false;
                        if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(decimal?))
                        { p.SetValue(obj, val.ObjToDecimal(), null); bset = true; }
                        if (p.PropertyType == typeof(int) || p.PropertyType == typeof(int?))
                        { p.SetValue(obj, val.ObjToInt(), null); bset = true; }
                        if (!bset)
                        { p.SetValue(obj, val, null); }
                    }

                }
            }
            return obj;
        }

        public static List<T> ToList<T>(this DataTable dt)
        {
            var l = new List<T>();
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                var t = dt.Rows[k].ToObj<T>();
                l.Add(t);
            }
            return l;
        }
    }
}
